// stores/counter.js  在pinia中，getters和state中不能使用相同的名字，但是vuex中可以使用相同的名字
import { defineStore,createPinia } from 'pinia'
import { createApp } from 'vue'; // 拿过来
import app from '../App.vue' // 拿过来
 
// const store = createPinia(); // 创建pinia实例
 
// createApp(app).use(store) // 直接给他挂上边，就解决啦
// 全局注册 store
// export function setupStore(app: App<Element>) {
//   app.use(store); // 挂载pinia
// }
//存储token 和 解析token 的用户
export const useAuthStore = defineStore('auth', {
	persist: { enabled: true },
    state: () => { //管理2个状态 一个是是否登录成功即token是否存在，二是解析的token里面所包含的数据
        return { isAuthenticated: false, user: {} }
    },
    // 也可以定义为
    // state: () => ({ count: 0 })
    getters: { //通过getters对状态state进行获取
        getAuthenticated: (state) => state.isAuthenticated,
        getUser: (state) => state.user
    },
    actions: {
        setAuth(isAuth: boolean) {//修改当前登录的状态
            if (isAuth) {
                this.isAuthenticated = isAuth; //在pinia中this指代state
            } else {
                this.isAuthenticated = false;
            }
        },
        setUser(user: any) { //解析的用户
            if (user) {
                this.user = user;
            } else {
                this.user = {};
            }
        },
		
    },
})

export const useShoppingCartsStore = defineStore('shoppingCarts', {
  state: () => ({
    shoppingCart: [] // 初始化为数组
  }),
  getters: {
    getNum: (state) => {
      return state.shoppingCart.reduce((total, item) => total + item.num, 0);
    },
    getIsAllCheck: (state) => {
      return state.shoppingCart.every((item) => item.check);
    },
    getCheckGoods: (state) => {
      return state.shoppingCart.filter((item) => item.check);
    },
    getCheckNum: (state) => {
      return state.shoppingCart.filter((item) => item.check).reduce((total, item) => total + item.num, 0);
    },
    getTotalPrice: (state) => {
      return state.shoppingCart.filter((item) => item.check).reduce((total, item) => total + item.price * item.num, 0);
    }
  },
  actions: {
    setShoppingCart(data) {
      this.shoppingCart = data;
    },
    unshiftShoppingCart(data) {
      this.shoppingCart.unshift(data);
    },
    updateShoppingCart(payload) {
      const item = this.shoppingCart[payload.key];
      if (item) {
        if (payload.prop === "num") {
          if (item.maxNum < payload.val || payload.val < 1) {
            return;
          }
        }
        item[payload.prop] = payload.val;
      }
    },
    addShoppingCartNum(productID) {
      const item = this.shoppingCart.find(item => item.productID === productID);
      if (item && item.num < item.maxNum) {
        item.num++;
      }
    },
    deleteShoppingCart(id) {
      const index = this.shoppingCart
	  },
	checkAll ({ commit }, data) {
	  	    commit('checkAll', data);
	  	  }
	   }	
	  })
export { store };